package com.xywh.emergency_outbound.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseLazyFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.emergency_outbound.R;
import com.xywh.emergency_outbound.di.component.DaggerTab2Component;
import com.xywh.emergency_outbound.di.module.Tab2Module;
import com.xywh.emergency_outbound.mvp.contract.Tab2Contract;
import com.xywh.emergency_outbound.mvp.presenter.Tab2Presenter;
import com.xywh.emergency_outbound.mvp.ui.adapter.Tab2Adapter;
import com.xywh.emergency_outbound.mvp.ui.entity.CancelReceipt;
import com.xywh.emergency_outbound.mvp.ui.entity.ConfirmReceipt;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab2;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab2Fragment extends BaseLazyFragment<Tab2Presenter> implements Tab2Contract.View, OnRefreshListener, Tab2Adapter.IConfirmReceipt, OnLoadMoreListener {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private Tab2Adapter mAdapter;
    private List<Tab2.DataBean> mDataBeanList = new ArrayList<>();
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    public static Tab2Fragment newInstance() {
        Tab2Fragment fragment = new Tab2Fragment();
        return fragment;
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    @Subscriber(tag = "tab2EmgtransferList", mode = ThreadMode.POST)
    public void tab2EmgtransferList(int index) {
        clearData();
        getTab2Data();
    }

    private void clearData() {
        mStart = 1;
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    private void getTab2Data() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        map.put("startindex", String.valueOf(mStart));
        map.put("endindex", String.valueOf(mStart + mNum - 1));
        mPresenter.getTab2Data(map);
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab2Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab2Module(new Tab2Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab2, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
        ToolbarUtils.initToolbarTitleNoBack(view, this, "调拨订单");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(true);
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
//        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new Tab2Adapter(getActivity(), mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (mDataBeanList != null && mDataBeanList.size() > 0) {

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("itemsBeans", mDataBeanList.get(position));
                    Utils.navigation(getActivity(), RouterHub.ACTIVITY_ORDER_LIST, bundle);
                }
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void getTab2DataSuccess(Tab2 entityData) {
        if (entityData != null && entityData.getData() != null && entityData.getData().size() > 0) {

            mStart += entityData.getData().size();
            mDataBeanList.addAll(entityData.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void confirmReceiptSuccess(ConfirmReceipt entityData) {
        showMessage(entityData.getMessage());
        if (entityData.getCode() == 200) {
            clearData();
            getTab2Data();
        }
    }

    @Override
    public void cancelReceiptSuccess(CancelReceipt entityData) {
        showMessage(entityData.getMessage());
        if (entityData.getCode() == 200) {
            clearData();
            getTab2Data();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        clearData();
        getTab2Data();
        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getActivity(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void confirmReceipt(Tab2.DataBean dataBean) {
        showconfirmReceiptMessageNegativeDialog(dataBean);
    }

    @Override
    public void cancelReceipt(Tab2.DataBean dataBean) {
        showcancelReceiptMessageNegativeDialog(dataBean);
    }

    private void showcancelReceiptMessageNegativeDialog(Tab2.DataBean dataBean) {
        new QMUIDialog.MessageDialogBuilder(getContext())
                .setTitle("取消调拨单")
                .setMessage("确定要取消调拨单吗？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("id", String.valueOf(dataBean.getID()));
                        mPresenter.cancelReceipt(map);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showconfirmReceiptMessageNegativeDialog(Tab2.DataBean dataBean) {
        new QMUIDialog.MessageDialogBuilder(getContext())
                .setTitle("确认收货")
                .setMessage("确定要收货吗？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("id", String.valueOf(dataBean.getID()));
                        mPresenter.confirmReceipt(map);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getTab2Data();
        mRefreshLayout.finishLoadMore();
    }
}
